package b2.scene.fight
{
	import b2.config.*;
	import b2.net.*;
	import b2.player.*;
	import b2.scene.*;
	import b2.scene.fight.skills.Blink;
	import b2.scene.fight.skills.SkillHelper;
	import b2.scene.guide.*;
	import b2.util.*;
	import b2.widget.*;
	import b2.widget.fight.*;
	
	import com.greensock.*;
	import com.smartfoxserver.v2.entities.*;
	import com.smartfoxserver.v2.entities.variables.*;
	
	import flash.display.*;
	import flash.filters.ColorMatrixFilter;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.*;
	
	import org.flixel.*;
	import org.flixel.system.*;

	public class PlayState extends FlxState
	{
		//初始位移
		public static const OFFSET_X:uint = 87;
		public static const OFFSET_Y:uint = 7;
		//格子个数
		public static const TILE_NUM:uint = 13;
		//格子大小
		public static const TILE_WIDTH:uint = 45;
		//移动一步大小
		public static const STEP_WIDTH:uint = 15;
		//移动一步的格子数
		public static const STEP_NUM:uint = 39;
		//转弯冷却	
		public static const DIRECTION_COOLDOWN:int = 4;
		//我的坦克
		public var myTankId:int;
		//我的阵营
		public var mySide:int;
		//战斗剩余时间
		public var remainTime:int;
		//敌人出现信息
		private var enemyAppears:Array;
		//敌人存在个数
		private var enemyExistNum:int;
		//未出生的敌人个数
		private var enemyRemainNum:int;
		//格子地图
		public var tileMap:FlxTilemap;
		//轨迹层
		public var traceSprite:TraceSprite;
		//寻路长度（和格子地图对应）
		public var distances:Array;
		//草坪层
		public var topTileSprite:Sprite;
		
		//战役配置
		private var battleConfig:BattleConfig;
		//所有坦克（坦克id作为索引）
		public var tanks:Object;
		//所有子弹（子弹id作为索引）
		private var bullets:Object;
		//所有战场物品（物品id作为索引）
		private var dropItems:Object;
		//碰撞子弹组
		private var collideBulletGroup:FlxGroup;
		//子弹组
		private var bulletGroup:FlxGroup;
		//坦克组
		private var tankGroup:FlxGroup;
		//战场物品组
		private var dropItemGroup:FlxGroup;
		//战斗标志
		private var inFightFlag:Boolean;
		//关卡心跳
		private var timer:FlxTimer
		//改变方向冷却时间（秒）
		private var coolDown:int;
		//存在的BOSS数量
		private var bossCount:int;
		//目的地标志
		private var destFlag:FlxSprite;
		//是否为英雄模式
		public var isHeroMode:Boolean;
		
		public function PlayState(battleIndex:int, lastRemainTime:int)
		{
			super();
			battleConfig = Config.battleConfigs[battleIndex];
			bullets = new Object();
			tanks = new Object();
			dropItems = new Object();
			collideBulletGroup = new FlxGroup();
			bulletGroup = new FlxGroup();
			tankGroup = new FlxGroup();
			dropItemGroup = new FlxGroup();
			inFightFlag = true;
			var gameMode:int = FightScene.getInstance().gameMode;
			if (gameMode == FightScene.MODE_MATCH)
				remainTime = battleConfig.battleTime + lastRemainTime;
			else
				remainTime = battleConfig.battleTime;
			prepareEnemies();
		}
		
		private function prepareEnemies():void
		{
			bossCount = 0;
			enemyExistNum = 0;
			enemyRemainNum = 0;
			enemyAppears = new Array();
			var gameMode:int = FightScene.getInstance().gameMode;
			if (gameMode == FightScene.MODE_FRIEND)
			{
				var friend:PlayerInfo = PlayerInfoManager.getInstance().players[FightScene.getInstance().friendId];
				for (var i:int = 0; i < friend.tankPackage.tankList.length; i++)
				{
					var tankId:int = friend.tankPackage.tankList[i];
					if (tankId != friend.campTankId)
					{
						enemyAppears.push(tankId);
						if (++enemyRemainNum >= 17)
							break;
					}
				}
				enemyAppears.push(friend.campTankId);
				enemyRemainNum++;
			}
			else
			{
				if (battleConfig.enemyAppears != null)
				{
					for (i = 0; i < battleConfig.enemyAppears.length; i++)
					{
						var enemyAppearInfoStrs:Array = battleConfig.enemyAppears[i].split(",");
						var enemyAppear:EnemyAppearConfig = new EnemyAppearConfig();
						enemyAppear.enemyIndex = enemyAppearInfoStrs[0];
						enemyAppear.num = enemyAppearInfoStrs[1];
						enemyAppear.level = enemyAppearInfoStrs[2];
						if (enemyAppearInfoStrs.length > 3)
							enemyAppear.posX = enemyAppearInfoStrs[3];
						else
							enemyAppear.posX = -1;
						if (enemyAppearInfoStrs.length > 4)
							enemyAppear.posY = enemyAppearInfoStrs[4];
						else
							enemyAppear.posY = -1;
						if (enemyAppearInfoStrs.length > 5)
							enemyAppear.direction = enemyAppearInfoStrs[5];
						else
							enemyAppear.direction = -1;
						if (enemyAppearInfoStrs.length > 6)
							enemyAppear.bossLevel = enemyAppearInfoStrs[6];
						else
							enemyAppear.bossLevel = 0;
						//比赛战役，重新计算等级
						if (FightScene.getInstance().gameMode == FightScene.MODE_MATCH)
						{
							var matchConfig:MatchConfig = Config.matchConfigs[FightScene.getInstance().matchIndex];
							enemyAppear.level = matchConfig.difficulty;
							enemyAppear.bossLevel = enemyAppear.bossLevel > 0 ? 2 : 0;
						}
						if (enemyAppear.bossLevel > 0)
							bossCount++;
						enemyAppears.push(enemyAppear);
						enemyRemainNum += enemyAppear.num;
					}
				}
			}
		}
		
		override public function create():void
		{
			var campIndex:int = FightScene.getInstance().campIndex;
			var fortIndex:int = Config.campFortLink[campIndex];
			var fortConfig:FortressConfig = Config.fortressConfigs[fortIndex];
			//战场背景
			var battleBgr:String;
			var battleBgrFilter:Array;
			if (battleConfig.battleBgr != "")
			{
				battleBgr = battleConfig.battleBgr;
				battleBgrFilter = battleConfig.battleBgrFilter;
			}
			else
			{
				battleBgr = fortConfig.battleBgr;
				battleBgrFilter = fortConfig.battleBgrFilter;
			}
			var BattleBgr:Class = ResourceHelper.getInstance().getClassByName(battleBgr);
			ExternalImage.setData(BattleBgr, fortConfig.battleBgr, 585, 585, battleBgrFilter);
			add(new FlxSprite(OFFSET_X, OFFSET_Y, ExternalImage));
			//战场地图
			tileMap = new FlxTilemap();
			tileMap.x = OFFSET_X;
			tileMap.y = OFFSET_Y;
			
			var tileImage:String;
			if (battleConfig.tileImage != "")
				tileImage = battleConfig.tileImage;
			else
				tileImage = fortConfig.tileImage;
			var BattleTiles:Class = ResourceHelper.getInstance().getClassByName(tileImage);
			var battleTiles:Sprite = new BattleTiles();
			var mapTile:BitmapData = new BitmapData(135, 135, true , 0);
			mapTile.draw(battleTiles);
			ExternalImage.setData(BattleTiles, fortConfig.tileImage);
			tileMap.loadMap(battleConfig.map, ExternalImage, TILE_WIDTH, TILE_WIDTH, FlxTilemap.OFF, 0, 0);
			tileMap.setTileProperties(4, FlxObject.NONE);
			tileMap.setTileProperties(5, FlxObject.NONE);
			//基础地图
			add(tileMap);
			//轨迹层
			traceSprite = new TraceSprite();
			add(traceSprite);
			//初始化地图距离
			distances = new Array(STEP_NUM * STEP_NUM);
			updateMapDistances();
			//穿越火线, 阻击敌军
			if (battleConfig.goal == 2 || battleConfig.goal == 3)
			{
				addDestFlag(battleConfig.destX, battleConfig.destY);
			}
			//掉落物品层
			add(dropItemGroup);
			//子弹层
			add(bulletGroup);
			//坦克层
			add(tankGroup);
			//创建总部
			if (isHeroMode)
			{
				createBase(3);
				createBaseShell(1);
			}
			else if (battleConfig.baseHp > 0)
			{
				createBase(battleConfig.baseHp);
				createBaseShell(battleConfig.baseShell);
			}
			
			//铺设草地
			topTileSprite = new Sprite();
			//缓存
			topTileSprite.cacheAsBitmap = true;
			for (var i:int = 0; i < TILE_NUM; i++)
				for (var j:int = 0; j < TILE_NUM; j++)
				{
					if (tileMap.getTile(i, j) == 5)
					{
						var rect:Rectangle = new Rectangle(TILE_WIDTH * 2, TILE_WIDTH, TILE_WIDTH * 3, TILE_WIDTH * 2);  
						var pt:Point = new Point(0, 0);
						var bmd:BitmapData = new BitmapData(TILE_WIDTH, TILE_WIDTH, true, 0xFF0000);
						bmd.copyPixels(mapTile, rect, pt);
						var bitMap:Bitmap = new Bitmap(bmd);
						bitMap.x = OFFSET_X + TILE_WIDTH * i;
						bitMap.y = OFFSET_Y + TILE_WIDTH * j;
						topTileSprite.addChild(bitMap);
					}
				}
			FightScene.getInstance().effectTopLayer.addChild(topTileSprite);
			//创建我的坦克
			createMyTank();
			//战斗计时
			timer = new FlxTimer();
			timer.start(1, 999999, onTick);
			
			FlxG.stage.focus = FlxG.stage;
			GuideScene.getInstance().step++;
		}
		
		//显示目的地旗帜
		public function addDestFlag(destX:int, destY:int):void
		{
			var DestFlag:Class = ResourceHelper.getInstance().getClassByName("DestFlag");
			ExternalImage.setData(DestFlag, "DestFlag");
			destFlag = new FlxSprite(OFFSET_X + TILE_WIDTH * destX,	OFFSET_Y + TILE_WIDTH * destY);
			destFlag.loadGraphic(ExternalImage, true, false, TILE_WIDTH);
			destFlag.addAnimation("float", [0, 1], 4);
			destFlag.play("float");
			dropItemGroup.add(destFlag);
		}
		
		//移除目的地旗帜
		public function removeDestFlag():void
		{
			if (destFlag != null)
			{
				dropItemGroup.remove(destFlag);
				destFlag = null;
			} 
		}
		
		override public function update():void
		{
			updateMyTank();
			//基本碰撞
			FlxG.collide(collideBulletGroup, tileMap, onTilemapCollide);
			FlxG.collide(collideBulletGroup, tankGroup, onBulletTankCollide);
			FlxG.collide(collideBulletGroup, null, onBulletCollide);
			FlxG.collide(tankGroup, null, onTankCollide);
			FlxG.collide(tankGroup, dropItemGroup, onDropItemCollide);
			//子弹超过边界检查
			for (var i:int = 0; i < collideBulletGroup.members.length; i++)
			{
				var bullet:BulletSprite = collideBulletGroup.members[i];
				if (bullet != null && (bullet.x < OFFSET_X || bullet.y < OFFSET_Y || bullet.x + bullet.width > OFFSET_X + TILE_WIDTH * TILE_NUM ||
					bullet.y + bullet.height > OFFSET_Y + TILE_WIDTH * TILE_NUM))
				{
					explodeBullet(bullet.bulletId, true);
				}
			}
			super.update();
		}
		
		private function updateMyTank():void
		{
			var myTank:TankSprite = this.tanks[myTankId];
			if (myTank == null)
				return;
			//16, 疯狂状态
			if (myTank.tankEffect.hasEffect(16))
			{
				FightScene.getInstance().showBottomMessage("<font color='#FF0000'>疯狂</font>状态下不受控制！");
				return;
			}
			//10, 时间停止
			else if (myTank.tankEffect.hasEffect(10))
			{
				FightScene.getInstance().showBottomMessage("<font color='#FF0000'>时间停止</font>状态下不受控制！");
				return;
			} 
			if (FlxG.mouse.justPressed())
			{
				onMousePressed();
			}
			else
			{
				onKeyPressed();
			}
			var rightPane:BattleRightPane = FightScene.getInstance().rightPane;
			//武器快捷键
			if (FlxG.keys.justPressed("ONE") || FlxG.keys.justPressed("U"))
				rightPane.triggerWeapon(6);
			else if (FlxG.keys.justPressed("TWO") || FlxG.keys.justPressed("I"))
				rightPane.triggerWeapon(7);
			else if (FlxG.keys.justPressed("THREE") || FlxG.keys.justPressed("O"))
				rightPane.triggerWeapon(8);
			else if (FlxG.keys.justPressed("FOUR") || FlxG.keys.justPressed("P"))
				rightPane.triggerWeapon(9);
		}
		
		//鼠标操作
		private function onMousePressed():void
		{
			var myTank:TankSprite = this.tanks[myTankId];
			if (FlxG.mouse.x >= OFFSET_X && FlxG.mouse.x <= OFFSET_X + TILE_WIDTH * TILE_NUM &&
				FlxG.mouse.y >= OFFSET_Y && FlxG.mouse.y <= OFFSET_Y + TILE_WIDTH * TILE_NUM)
			{
				var targetX:Number = int((FlxG.mouse.x - OFFSET_X) / TILE_WIDTH) * TILE_WIDTH + OFFSET_X;
				var targetY:Number = int((FlxG.mouse.y - OFFSET_Y) / TILE_WIDTH) * TILE_WIDTH + OFFSET_Y;
				var fireTime:int = getTimer();
				if (myTank.pathSpeed == 0)
				{
					myTank.direction = getMouseDirection();
					if (fireTime - myTank.lastFireTime >= myTank.fireCooldown)
						myTank.fireBullet(0, 0, -1, -1, -1, myTank.direction);
				}
				if (myTank.tankEffect.hasEffect(EffectConfig.COLLIDE))
					myTank.tankEffect.removeEffect(EffectConfig.COLLIDE);
				if (!myTank.move(targetX, targetY))
				{
					if (fireTime - myTank.lastFireTime >= myTank.fireCooldown)
						myTank.fireBullet(0, 0, -1, -1, -1, myTank.direction);
				}
				myTank.flagAI = true;
			}
		}
		
		//键盘操作
		private function onKeyPressed():void
		{
			var myTank:TankSprite = this.tanks[myTankId];
			//坦克整格坐标
			var targetX:int;
			var targetY:int;
			var availableToGo:Boolean = false;
			//13, 混乱状态
			if (FlxG.keys.A || FlxG.keys.LEFT)
			{
				//计算当前坦克整格坐标(向左走，往右取)
				targetX = OFFSET_X + int(Math.ceil((myTank.x - OFFSET_X) / STEP_WIDTH)) * STEP_WIDTH;
				targetY = OFFSET_Y + int(Math.round((myTank.y - OFFSET_Y) / STEP_WIDTH)) * STEP_WIDTH;
				availableToGo = targetX - STEP_WIDTH >= OFFSET_X && !tileMap.overlapsPoint(new FlxPoint(targetX - STEP_WIDTH, targetY + 1)) && !tileMap.overlapsPoint(new FlxPoint(targetX - STEP_WIDTH, targetY + TILE_WIDTH - 1));
				myTankTurnRound(3, availableToGo, targetX, targetY, targetX - STEP_WIDTH, targetY);
				myTank.flagAI = false;
			}
			else if (FlxG.keys.D || FlxG.keys.RIGHT)
			{
				//计算当前坦克整格坐标(向右走，往左取)
				targetX = OFFSET_X + int(Math.floor((myTank.x - OFFSET_X) / STEP_WIDTH)) * STEP_WIDTH;
				targetY = OFFSET_Y + int(Math.round((myTank.y - OFFSET_Y) / STEP_WIDTH)) * STEP_WIDTH;
				
				availableToGo = targetX + STEP_WIDTH + TILE_WIDTH <= OFFSET_X + TILE_WIDTH * TILE_NUM && !tileMap.overlapsPoint(new FlxPoint(targetX + STEP_WIDTH -1 + TILE_WIDTH, targetY + 1)) && !tileMap.overlapsPoint(new FlxPoint(targetX + STEP_WIDTH -1 + TILE_WIDTH, targetY + TILE_WIDTH - 1));
				myTankTurnRound(1, availableToGo, targetX, targetY, targetX + STEP_WIDTH, targetY);
				myTank.flagAI = false;
			}
			else if (FlxG.keys.W || FlxG.keys.UP)
			{
				//计算当前坦克整格坐标(向上走，往下取)
				targetX = OFFSET_X + int(Math.round((myTank.x - OFFSET_X) / STEP_WIDTH)) * STEP_WIDTH;
				targetY = OFFSET_Y + int(Math.ceil((myTank.y - OFFSET_Y) / STEP_WIDTH)) * STEP_WIDTH;
				
				availableToGo = targetY - STEP_WIDTH >= OFFSET_Y &&!tileMap.overlapsPoint(new FlxPoint(targetX + 1, targetY - STEP_WIDTH)) && !tileMap.overlapsPoint(new FlxPoint(targetX + TILE_WIDTH - 1, targetY - STEP_WIDTH))
				myTankTurnRound(0, availableToGo, targetX, targetY, targetX, targetY - STEP_WIDTH);	
				myTank.flagAI = false;
			}
			else if (FlxG.keys.S || FlxG.keys.DOWN)
			{
				//计算当前坦克整格坐标(向下走，往上取)
				targetX = OFFSET_X + int(Math.round((myTank.x - OFFSET_X) / STEP_WIDTH)) * STEP_WIDTH;
				targetY = OFFSET_Y + int(Math.floor((myTank.y - OFFSET_Y) / STEP_WIDTH)) * STEP_WIDTH;
				
				availableToGo = targetY + STEP_WIDTH + TILE_WIDTH <= OFFSET_Y + TILE_WIDTH * TILE_NUM && !tileMap.overlapsPoint(new FlxPoint(targetX + 1, targetY + STEP_WIDTH -1 + TILE_WIDTH)) && !tileMap.overlapsPoint(new FlxPoint(targetX + TILE_WIDTH - 1, targetY + STEP_WIDTH -1 + TILE_WIDTH));
				myTankTurnRound(2, availableToGo, targetX, targetY, targetX, targetY + STEP_WIDTH);	
				myTank.flagAI = false;
			}
			if (FlxG.keys.justPressed("SPACE") || FlxG.keys.justPressed("J"))
			{
				//14, 炮弹封印
				if (myTank.tankEffect.hasEffect(14))
				{
					FightScene.getInstance().showBottomMessage("<font color='#FF0000'>封印</font>状态下不能发炮！");
				}
				else
				{
					var fireTime:int = getTimer();
					if (fireTime - myTank.lastFireTime >= myTank.fireCooldown)
					{
						myTank.fireBullet(0, 0, -1, -1, -1, myTank.direction);
					}
					else
					{
						FightScene.getInstance().showBottomMessage("发炮速度过快，炮管冷却中！");
					}
				}
				myTank.flagAI = false;
			}
		}
		
		private function myTankTurnRound(direction:int, availableToGo:Boolean, fromX:int, fromY:int, toX:int, toY:int):void
		{
			var myTank:TankSprite = this.tanks[myTankId];
			if (myTank.direction != direction)
			{
				myTank.direction = direction;
				coolDown = DIRECTION_COOLDOWN;
			}
			else
			{
				if (--coolDown < 0 && myTank.velocity.x == 0 && myTank.velocity.y == 0 && availableToGo)
				{
					myTank.move(toX, toY);
				}
			}
		}
		
		private function getMouseDirection():int
		{
			var myTank:TankSprite = this.tanks[myTankId];
			var diffX:Number = FlxG.mouse.x - myTank.x - TILE_WIDTH / 2;
			var diffY:Number = FlxG.mouse.y - myTank.y - TILE_WIDTH / 2;
			var direction:int;
			if (Math.abs(diffY) > Math.abs(diffX) && diffY < 0)
				direction = 0;
			else if (Math.abs(diffX) > Math.abs(diffY) && diffX > 0)
				direction = 1;
			else if (Math.abs(diffY) > Math.abs(diffX) && diffY >= 0)
				direction = 2;
			else
				direction = 3;
			return direction;
		}

		//坐标转化为格点索引(1Grid = 1/3 格)
		public function posToGridIndex(posX:int, posY:int):int
		{
			var widthInSteps:int = PlayState.STEP_NUM;
			var stepWidth:int = PlayState.STEP_WIDTH;
			return int((posY- tileMap.y) / stepWidth) * widthInSteps + int((posX - tileMap.x) / stepWidth);
		}
		
		//格点索引转化为坐标(1Grid = 1/3 格)
		public function gridIndexToPos(gridIndex:int):Array
		{
			var widthInSteps:int = PlayState.STEP_NUM;
			var stepWidth:int = PlayState.STEP_WIDTH;
			return [tileMap.x + gridIndex % widthInSteps * stepWidth, 
				tileMap.y + int(gridIndex / widthInSteps) * stepWidth];
		}
		
		//检查格点是否碰撞(1Grid = 1/3 格)
		private function checkGridCollision(gridIndex:int):Boolean
		{
			var stepWidth:int = PlayState.STEP_WIDTH;
			var pos:Array = gridIndexToPos(gridIndex);
			var offsetX:Array = [stepWidth * 0.5, stepWidth * 0.5, stepWidth * 2.5, stepWidth * 2.5];
			var offsetY:Array = [stepWidth * 0.5, stepWidth * 2.5, stepWidth * 0.5, stepWidth * 2.5];
			for (var i:int = 0; i < 4; i++)
			{
				var posX:Number = pos[0] + offsetX[i];
				var posY:Number = pos[1] + offsetY[i];
				if (posX < tileMap.x || posX > tileMap.x + tileMap.width || posY < tileMap.y || posY > tileMap.y + tileMap.height)
					return true;
				if (tileMap.overlapsPoint(new FlxPoint(posX, posY)))
					return true;
			}
			return false;
		}
		
		//更新地图距离
		private function updateMapDistances():void
		{
			var MAX_DIST:int = 999999;
			for (var i:int = 0; i < distances.length; i++)
			{
				if (checkGridCollision(i))
					distances[i] = -1;
				else
					distances[i] = MAX_DIST;
			}
		}
		
		private function onTilemapCollide(object1:FlxObject, object2:FlxObject):void
		{
			var bullet:BulletSprite;
			if (object1 is BulletSprite)
			{
				bullet = object1 as BulletSprite;
			}
			else if (object2 is BulletSprite)
			{
				bullet = object2 as BulletSprite;
			}
			var frontPoint:FlxPoint = bullet.getFrontPoint();
			var tileX:int = (frontPoint.x - OFFSET_X) / TILE_WIDTH;
			var tileY:int = (frontPoint.y - OFFSET_Y) / TILE_WIDTH;
			var tile:int = tileMap.getTile(tileX, tileY);
			if (tile == 1)
				updateTile(tileX, tileY, 0, true);
			if (tile != 3 && tile != 4 && tile != 5)
				explodeBullet(bullet.bulletId, true);
		}
		
		private function onTankCollide(object1:FlxObject, object2:FlxObject):void
		{
			if (object1 is TankSprite && object2 is TankSprite)
			{
				var tank1:TankSprite = object1 as TankSprite;
				var tank2:TankSprite = object2 as TankSprite;
				if (tank1.side != tank2.side)
				{
					tank1.onCollideByTank(tank2);
					tank2.onCollideByTank(tank1);
				}
			}
		}
		
		private function onBulletCollide(object1:FlxObject, object2:FlxObject):void
		{
			if (object1 is BulletSprite && object2 is BulletSprite)
			{
				var bullet1:BulletSprite = object1 as BulletSprite;
				var bullet2:BulletSprite = object2 as BulletSprite;
				if (bullet1.side != bullet2.side && bullet1.direction != bullet2.direction)
				{
					explodeBullet(bullet1.bulletId, true);
					explodeBullet(bullet2.bulletId, true);
				}
			}
		}
		
		private function onBulletTankCollide(object1:FlxObject, object2:FlxObject):void
		{
			var bullet:BulletSprite;
			var tank:TankSprite;
			if (object1 is BulletSprite)
			{
				bullet = object1 as BulletSprite;
				tank = object2 as TankSprite;
			}
			else if (object2 is BulletSprite)
			{
				bullet = object2 as BulletSprite;
				tank = object1 as TankSprite;
			}
			//子弹击中不同势力的坦克才有伤害
			if (tank.side != bullet.side)
			{
				tank.onCollideByBullet(bullet);
			}
		}
		
		private function onDropItemCollide(object1:FlxObject, object2:FlxObject):void
		{
			var dropItem:DropItemSprite;
			var tank:TankSprite;
			if (object1 is DropItemSprite)
			{
				dropItem = object1 as DropItemSprite;
				tank = object2 as TankSprite;
			}
			else if (object2 is DropItemSprite)
			{
				dropItem = object2 as DropItemSprite;
				tank = object1 as TankSprite;
			}
			if (dropItem == null || !dropItem.alive)
				return;
			if (tank.side == TankSprite.SIDE_ME)
				BSound.getInstance().playEffect("SoundFetchItem");
			removeDropItem(dropItem.itemId, true);
			var message:String = "";
			//宝箱
			if (dropItem.itemIndex == 0 || dropItem.itemIndex > 9)
			{
				GuideScene.getInstance().step++;
				FightScene.getInstance().addAwardList(tank.tankId, dropItem.objectIndex, dropItem.basicLevel, dropItem.strengthenLevel, 
					dropItem.objectNum);
				var objConfig:CommonObjConfig = Config.objectConfigs[dropItem.objectIndex];
				var objFullName:String;
				var numName:String;
				if (objConfig.noBasicLevel)
				{
					objFullName = objConfig.name;
					numName = "";
				}
				else if (objConfig.noStrengthenLevel)
				{
					objFullName = Config.basicConfig.objectBasicLevel[dropItem.basicLevel] + "的" + objConfig.name;
					numName = "枚";
				}
				else
				{
					objFullName = Config.basicConfig.objectBasicLevel[dropItem.basicLevel] + 
						Config.basicConfig.objectStrengthenLevel[dropItem.strengthenLevel] + "的" + objConfig.name;
					numName = "个";
				}
				message = "获得<font color='#FF0000'>" + objFullName + "</font><font color='#00AA00'> " + dropItem.objectNum + " </font>" + numName;
			}
			//生命回复
			else if (dropItem.itemIndex == DropItemConfig.HP)
			{
				updateTankStatus(tank.tankId, -1, tank.currentHp, 500, 0, 0, false);
				message = "恢复<font color='#FF0000'>生命</font><font color='#00AA00'> 500 </font>点";
			}
			//能量回复
			else if (dropItem.itemIndex == DropItemConfig.EP)
			{
				updateTankStatus(tank.tankId, -1, 0, 0, tank.currentEp, 550, false);
				message = "恢复<font color='#FF0000'>能量</font><font color='#00AA00'> 550 </font>点";
			}
			//攻击增强
			else if (dropItem.itemIndex == DropItemConfig.AP_PLUS)
			{
				addTankEffect(tank.tankId, -1, 1, 30, 500, 0);
			}
			//暴击率增加
			else if (dropItem.itemIndex == DropItemConfig.CA_RATIO_PLUS)
			{
				addTankEffect(tank.tankId, -1, 2, 30, 150, 0);
			}
			//增加生命
			else if (dropItem.itemIndex == DropItemConfig.LIFE_PLUS)
			{
				addTankLife(tank.tankId, 1, true);
				message = "增加<font color='#FF0000'>生命</font><font color='#00AA00'> 1 </font>条";
			}
			//无敌
			else if (dropItem.itemIndex == DropItemConfig.INVULNERABLE)
			{
				addTankEffect(tank.tankId, -1, 0, 10, 0, 0);
			}
			//炸弹
			else if (dropItem.itemIndex == DropItemConfig.BOMB)
			{
				//杀死所有非BOSS坦克
				for (var tankIdStr:String in tanks)
				{
					var eachTank:TankSprite = tanks[tankIdStr];
					if ((eachTank.side != tank.side) && eachTank.bossLevel <= 0)
					{
						updateTankStatus(eachTank.tankId, tank.tankId, 0, -eachTank.currentHp, 0, 0, false);
					}
				}
				message = "使用了<font color='#FF0000'>炸弹</font>";
			}
			//定身
			else if (dropItem.itemIndex == DropItemConfig.MOVE_STOP)
			{
				//定身所有坦克
				for (tankIdStr in tanks)
				{
					eachTank = tanks[tankIdStr];
					if ((eachTank.side != tank.side) && eachTank.bossLevel <= 0)
					{
						addTankEffect(eachTank.tankId, tank.tankId, EffectConfig.MOVE_STOP, 10, 0, 0);
					}
				}
				message = "使用了<font color='#FF0000'>定身</font>";
			}
			//头盔
			else if (dropItem.itemIndex == DropItemConfig.HELMET)
			{
				addTankEffect(tank.tankId, -1, EffectConfig.HELMET, 18, 0, 0);
			}
			if (message.length > 0)
			{
				message = "<font color='#0000FF'>" + tank.tankName + "</font>" + message;
				FightScene.getInstance().showBottomMessage(message, true);
			}
		}
		
		public override function draw():void
		{
			super.draw();
			var myTank:TankSprite = this.tanks[myTankId];
			if (myTank != null && myTank.path != null)
			{
				traceSprite.drawPath(myTank.path);
			}
		}
		
		public function updateTile(posX:int, posY:int, tile:int, syncFlag:Boolean = false):void
		{
			tileMap.setTile(posX, posY, tile);
			updateMapDistances();
		}
		
		//播放坦克影片
		public function playTankMovie(movieIndex:int, tankId:int, syncFlag:Boolean = false):void
		{
			var tank:TankSprite = tanks[tankId];
			if (tank != null)
			{
				var movieConfig:MovieConfig = Config.movieConfigs[movieIndex];
				//影片动画
				var MovieImage:Class = ResourceHelper.getInstance().getClassByName(movieConfig.imgName);
				var fps:int = movieConfig.imgFps > 0 ? movieConfig.imgFps : 10;
				var movieImage:BasicMc = new BasicMc(MovieImage, fps, false, true);
				if (movieConfig.movieFilter != null)
					movieImage.filters = [new ColorMatrixFilter(movieConfig.movieFilter)];
				if (movieConfig.imgWidth > 0)
				{
					movieImage.width = movieConfig.imgWidth;
					if (movieConfig.imgHeight > 0)
						movieImage.height = movieConfig.imgHeight;
					else
						movieImage.scaleY = movieImage.scaleX;
				}
				movieImage.x = movieConfig.imgPosX - PlayState.TILE_WIDTH / 2;
				movieImage.y = movieConfig.imgPosY - PlayState.TILE_WIDTH / 2;
				tank.tankEffect.effectContainer.addChild(movieImage);
			}
		}
		
		//播放固定影片
		public function playFixMovie(movieIndex:int, posX:int, posY:int, direction:int = 0, syncFlag:Boolean = false):void
		{
			var movieConfig:MovieConfig = Config.movieConfigs[movieIndex];
			var MovieImage:Class = ResourceHelper.getInstance().getClassByName(movieConfig.imgName);
			var fps:int = movieConfig.imgFps > 0 ? movieConfig.imgFps : 10;
			var movie:BasicMc = new BasicMc(MovieImage, fps, false, true);
			if (movieConfig.movieFilter != null)
				movie.filters = [new ColorMatrixFilter(movieConfig.movieFilter)];
			movie.x = movieConfig.imgPosX + posX;
			movie.y = movieConfig.imgPosY + posY;
			if (movieConfig.imgWidth > 0)
			{
				movie.width = movieConfig.imgWidth;
				if (movieConfig.imgHeight > 0)
					movie.height = movieConfig.imgHeight;
				else
					movie.scaleY = movie.scaleX;
			}
			movie.rotation = direction * 90;
			FightScene.getInstance().effectTopLayer.addChild(movie);
		}
		
		//增加坦克生命
		public function addTankLife(targetTankId:int, lifePlus:int, syncFlag:Boolean = false):void
		{
			var event:FightEvent = new FightEvent(FightEvent.TANK_LIFE_PLUS);
			event.targetTankId = targetTankId;
			event.lifePlus = lifePlus;
			FightScene.getInstance().eventDispatcher.dispatchEvent(event);
		}
		
		//targetTankId, 目标坦克; conductTankId, 施为坦克
		public function addTankEffect(targetTankId:int, conductTankId:int, effectIndex:int, effectDuration:int, effectValue:int, effectValue2:int):void
		{
			var tank:TankSprite = tanks[targetTankId];
			if (tank != null)
			{
				tank.tankEffect.addEffect(effectIndex, effectDuration, conductTankId, effectValue, effectValue2);
			}
		}

		//targetTankId, 目标坦克 
		public function tankTweenLiteTo(targetTankId:int, milliSeconds:Number, direction:int, fromX:int, fromY:int, toX:int, toY:int, alpha:Number = 1.0):void
		{
			var tank:TankSprite = tanks[targetTankId];
			tank.stopFollowingPath(true);
			tank.tweenLiteFlag = true;
			tank.direction = direction;
			tank.x = fromX;
			tank.y = fromY;
			TweenLite.to(tank, milliSeconds / 1000, {x:toX, y:toY, alpha:alpha, onComplete: onTankTweenLiteFinished, onCompleteParams: [targetTankId]});
		}
		
		private function onTankTweenLiteFinished(targetTankId:int):void
		{
			var tank:TankSprite = tanks[targetTankId];
			if (tank != null)
				tank.tweenLiteFlag = false;
		}

		//targetTankId, 目标坦克; conductTankId, 施为坦克
		public function updateTankStatus(targetTankId:int, conductTankId:int, healthPoint:int, healthPointDelta:int, energyPoint:int, energyPointDelta:int,  
			criticalFlag:Boolean = false):void
		{
			var tank:TankSprite = tanks[targetTankId];
			if (tank != null)
			{
				var fight:FightScene = FightScene.getInstance();
				var numEffect:PopNumberEffect;
				if (healthPointDelta > 0 || (healthPointDelta < 0 && !tank.tankEffect.hasEffect(0)))
				{
					tank.currentHp = healthPoint;
					tank.currentHp += healthPointDelta;
					//HP变化动画
					var fontSize:int;
					if (criticalFlag)
						fontSize = 20;
					else
						fontSize = 10;
					numEffect = new PopNumberEffect(healthPointDelta, fontSize, 0xFF0000, 0xFFFF00, true);
					numEffect.x = tank.x;
					numEffect.y = tank.y;
					fight.effectLayer.addChild(numEffect);
				}
				if (energyPointDelta > 0 || (energyPointDelta < 0 && !tank.tankEffect.hasEffect(0)))
				{
					tank.currentEp = energyPoint;
					tank.currentEp += energyPointDelta;
					//EP变化动画, 8, 能量吞噬; 11, 能量护盾
					if (energyPointDelta > 0 || tank.tankEffect.hasEffect(8) || tank.tankEffect.hasEffect(11))
					{
						numEffect = new PopNumberEffect(energyPointDelta, 10, 0x0000FF, 0xFFFF00, false);
						numEffect.x = tank.x;
						numEffect.y = tank.y;
						fight.effectLayer.addChild(numEffect);
					}
				}
				
				//更新面板信息
				var event:FightEvent;
				if (tank.tankId == myTankId)
				{
					event = new FightEvent(FightEvent.TANK_STATUS_CHANGE);
					event.targetTankId = targetTankId;
					event.healthPoint = tank.currentHp;
					event.hpDelta = healthPointDelta;
					event.energyPoint = tank.currentEp;
					event.epDelta = energyPointDelta;
					fight.eventDispatcher.dispatchEvent(event);
				}
				if (tank.currentHp <= 0)
				{
					killTank(targetTankId, conductTankId);
				}
			}
		}
		
		public function killTank(targetTankId:int, conductTankId:int):void
		{
			var fight:FightScene = FightScene.getInstance();
			var tank:TankSprite = tanks[targetTankId];
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			//敌军个数统计
			if (tank.side == TankSprite.SIDE_COMP || tank.side == TankSprite.SIDE_FRIEND)
			{
				enemyExistNum--;
				if (tank.bossLevel > 0)
					this.bossCount--;
			}
			//结算击杀奖励
			if (conductTankId == myTankId)
			{
				//敌军势力
				if (tank.side == TankSprite.SIDE_COMP)
				{
					var enemyConfig:EnemyConfig = Config.enemyConfigs[tank.enemyIndex];
					if (enemyConfig.oil > 0)
						fight.addAwardList(conductTankId, CommonObjConfig.OIL, 0, 0, enemyConfig.oil * tank.level);
					if (enemyConfig.experience > 0)
						fight.addAwardList(conductTankId, CommonObjConfig.EXP, 0, 0, enemyConfig.experience * tank.level);
				}
				//对战好友势力
				else if (tank.side == TankSprite.SIDE_FRIEND)
				{
					var targetTank:TankInfo = PlayerInfoManager.getInstance().tanks[targetTankId];
					var myTank:TankInfo = PlayerInfoManager.getInstance().tanks[conductTankId];
					var gainHonour:int = Math.max(targetTank.fightPoint - myTank.fightPoint, 1);
					fight.addAwardList(conductTankId, CommonObjConfig.HONOUR, 0, 0, gainHonour);
					fight.addAwardList(targetTankId, CommonObjConfig.HONOUR, 0, 0, -gainHonour);
				}
			} 
			delete tanks[targetTankId];
			tank.kill();
			tank.destroy();
			
			var event:FightEvent = new FightEvent(FightEvent.TANK_KILLED);
			event.targetTankId = targetTankId;
			event.conductTankId = conductTankId;
			fight.eventDispatcher.dispatchEvent(event);
		}
		
		public function updateTankMove(tankId:int, posX:Number, posY:Number, destX:Number, destY:Number):void
		{
			var tank:TankSprite = tanks[tankId];
			if (tank != null)
			{
				//如果位移超过了2格的差距就更新当前坐标
				if (Math.abs(tank.x - posX) > PlayState.TILE_WIDTH * 2 || Math.abs(tank.y - posY) > PlayState.TILE_WIDTH * 2)
				{
					tank.x = posX;
					tank.y = posY;	
				} 
				tank.move(destX, destY);
			}
		}
		
		public function updateTankDirection(tankId:int, direction:int):void
		{
			var tank:TankSprite = tanks[tankId];
			if (tank != null)
			{
				tank.direction = direction;
			}
		}
		
		public function explodeBullet(bulletId:int, syncFlag:Boolean = false):void
		{
			var bullet:BulletSprite = bullets[bulletId];
			if (bullet != null)
			{
				delete bullets[bullet.bulletId];
				bullet.kill();
				bullet.destroy();
			}
		}
		
		public function createDropItem(itemId:int, itemIndex:int, side:int, fromX:int, fromY:int, posX:int, posY:int, objectIndex:int, basicLevel:int, 
			strengthenLevel:int, objectNum:int, syncFlag:Boolean = false):void
		{
			var dropItem:DropItemSprite = new DropItemSprite(itemId, itemIndex, side);
			dropItem.objectIndex = objectIndex;
			dropItem.basicLevel = basicLevel;
			dropItem.strengthenLevel = strengthenLevel;
			dropItem.objectNum = objectNum;
			dropItem.x = posX;
			dropItem.y = posY;
			dropItem.alive = false;
			dropItems[dropItem.itemId] = dropItem;
			dropItemGroup.add(dropItem);
			var dist:Number = Math.sqrt((fromX - posX) * (fromX - posX) + (fromY - posY) * (fromY - posY)) / 600;  
			TweenLite.from(dropItem, dist, {x: fromX, y: fromY, onComplete:onDropItemCreated, onCompleteParams: [dropItem]});
		}
		
		private function onDropItemCreated(dropItem:DropItemSprite):void
		{
			dropItem.alive = true;
		}
		
		public function removeDropItem(itemId:int, syncFlag:Boolean = false):void
		{
			var dropItem:DropItemSprite = dropItems[itemId];
			if (dropItem != null)
			{
				dropItem.alive = false;
				var timeline:TimelineLite = new TimelineLite({onComplete:killDropItem, onCompleteParams: [dropItem]});
				//得到物品动画
				timeline.append(new TweenLite(dropItem.scale, 0.3, {x:1, y:1}));
				timeline.append(new TweenLite(dropItem, 1.5, {alpha:0}));
				delete dropItems[itemId];
			}
		}
		
		private function killDropItem(dropItem:DropItemSprite):void
		{
			TweenLite.delayedCall(1, dropItem.destroy);
			dropItem.kill();
			dropItem.destroy();
		}
		
		public function createBullet(bulletId:int, bulletIndex:int, tankId:int, side:int, attackPoint:int, direction:int, posX:Number, posY:Number, 
			velocityX:Number, velocityY:Number, criticalFlag:Boolean, effectIndex:int = -1, effectValue:int = -1, effectDuration:int = -1, syncFlag:Boolean = false):BulletSprite
		{
			var bullet:BulletSprite = new BulletSprite(bulletId, bulletIndex, tankId, side, attackPoint, criticalFlag, effectIndex, effectValue, effectDuration);
			bullet.direction = direction;
			bullet.x = posX;
			bullet.y = posY;
			bullet.velocity.x = velocityX; 
			bullet.velocity.y = velocityY;
			bullets[bulletId] = bullet;
			bulletGroup.add(bullet);
			collideBulletGroup.add(bullet);
			return bullet;
		}
		
		private function createBase(baseHp:int):void
		{
			createTankNow(0, 10009, "", TankSprite.SIDE_BASE, 1, OFFSET_X + TILE_WIDTH * 6, OFFSET_Y + TILE_WIDTH * 12, baseHp, 0, 0, 0, 99999, 0, 0, -1, 0, 0);
		}
		
		private function createBaseShell(tile:int, syncFlag:Boolean = false):void
		{
			updateTile(5, 12, tile, syncFlag);
			updateTile(5, 11, tile, syncFlag);
			updateTile(6, 11, tile, syncFlag);
			updateTile(7, 11, tile, syncFlag);
			updateTile(7, 12, tile, syncFlag);
		}
		
		public function createMyTank():void
		{
			//出生用户的坦克
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			this.myTankId = me.campTankId;
			var myCampTank:TankInfo = PlayerInfoManager.getInstance().tanks[me.campTankId];
			//自己在房间中索引
			var myRoomIndex:int = 0;
			this.mySide = 0;
			var birthInfoStrs:Array = battleConfig.birthPlace[myRoomIndex].split(",");
			var posX:Number = OFFSET_X + TILE_WIDTH * birthInfoStrs[0];
			var posY:Number = OFFSET_Y + TILE_WIDTH * birthInfoStrs[1];
			var direction:int = parseInt(birthInfoStrs[2]);
			createTank(myCampTank.id, myCampTank.index, me.nickname, mySide, direction, posX, posY, myCampTank.healthPoint, myCampTank.energyPoint, myCampTank.attackPoint, 
				myCampTank.criticalAttackRatio, myCampTank.armPoint, myCampTank.moveVelocity, myCampTank.fireCooldown, -1, me.title, 0);
		}
		
		public function createTank(tankId:int, tankIndex:int, tankName:String, side:int, direction:int, posX:Number, posY:Number, healthPoint:int, energyPoint:int, 
			attackPoint:int, criticalAttackRatio:int, armPoint:int, moveVelocity:int, fireCooldown:int, enemyIndex:int, level:int, bossLevel:int):void
		{
			if (tanks[tankId] != null)
			{
				DebugPane.getInstance().addInfo("createTank: tanks[tankId] != null");
				return;
			}
			DebugPane.getInstance().addInfo("createTank: (tankId, " + tankId + ")");
			var fight:FightScene = FightScene.getInstance();
			//电脑控制的坦克
			if (side == TankSprite.SIDE_COMP || side == TankSprite.SIDE_FRIEND)
			{
				enemyExistNum++;
				enemyRemainNum--;
				fight.leftPane.updateRemainEnemy(enemyRemainNum);
			}
			//提示信息
			if (bossLevel > 0)
			{
				var bossName:String;
				if (side == TankSprite.SIDE_COMP)
				{
					var enemyConfig:EnemyConfig = Config.enemyConfigs[enemyIndex];
					bossName = enemyConfig.name;
				}
				else
				{
					var tankConfig:TankConfig = Config.objectConfigs[tankIndex];
					bossName = tankConfig.name;
				}
				fight.showTopMessage("敌军首领<font color='#FF0000'>" + bossName + "</font>出现");	
			}
			startBornEffect(posX, posY);
			var event:FightEvent = new FightEvent(FightEvent.TANK_CREATED);
			event.targetTankId = tankId;
			fight.eventDispatcher.dispatchEvent(event);
			TweenLite.delayedCall(2, createTankNow, [tankId, tankIndex, tankName, side, direction, posX, posY, healthPoint, energyPoint, attackPoint, 
			criticalAttackRatio, armPoint, moveVelocity, fireCooldown, enemyIndex, level, bossLevel, true]);
		}
		
		private function startBornEffect(posX:Number, posY:Number):void
		{
			var BornStar:Class = ResourceHelper.getInstance().getClassByName("BornStar");
			var bornStar:BasicMc = new BasicMc(BornStar, 15, false, true);
			bornStar.width = 50;
			bornStar.scaleY = bornStar.scaleX;
			bornStar.x = posX;
			bornStar.y = posY;
			FightScene.getInstance().effectLayer.addChild(bornStar);
		}
		
		public function createTankNow(tankId:int, tankIndex:int, tankName:String, side:int, direction:int, posX:Number, posY:Number, healthPoint:int, energyPoint:int, 
			attackPoint:int, criticalAttackRatio:int, armPoint:int, moveVelocity:int, fireCooldown:int, enemyIndex:int, level:int, bossLevel:int, syncFlag:Boolean = false):void
		{
			if (tanks[tankId] != null)
			{
				DebugPane.getInstance().addInfo("createTankNow: tanks[tankId] != null");
				return;
			}
			DebugPane.getInstance().addInfo("createTankNow: (tankId, " + tankId + ")");
			var tank:TankSprite = new TankSprite(tankId, tankIndex, tankName, side, healthPoint, energyPoint, attackPoint, criticalAttackRatio, armPoint, 
				moveVelocity, fireCooldown, enemyIndex, level, bossLevel);
			tank.direction = direction;
			tank.x = posX;
			tank.y = posY;
			tankGroup.add(tank);
			tanks[tankId] = tank;
			//出生时无敌
			if (tank.side == TankSprite.SIDE_ME)
				tank.tankEffect.addEffect(0, 5, tankId, 0, 0);
		}
		
		public function getRandEmptyPos():Point
		{
			var emptyPoints:Array = new Array();
			for (var posX:int = 0; posX < this.tileMap.widthInTiles; posX++)
			{
				for (var posY:int = 0; posY < this.tileMap.heightInTiles; posY++)
				{
					if (tileMap.getTile(posX, posY) == 0 && !(posX == 6 && posY == 12))
					{
						emptyPoints.push(new Point(posX, posY));
					}
				}
			}
			var randIndex:int = Math.random() * emptyPoints.length;
			return emptyPoints[randIndex];
		}
		
		//得到获胜方
		private function getWinSide():int
		{
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			//在新手引导中
			if (GuideScene.getInstance().enabled && GuideScene.getInstance().step < 11)
				return TankSprite.SIDE_NULL;
			var mySideLife:int = FightScene.getInstance().leftPane.getLifeTotal();
			//我军全灭
			if (mySideLife <= 0)
				return TankSprite.SIDE_COMP;
			//主基地被灭
			else if ((battleConfig.baseHp > 0 || this.isHeroMode) && this.tanks[0] == null)
				return TankSprite.SIDE_COMP;
			//全歼敌军
			else if (this.enemyExistNum <= 0 && this.enemyRemainNum <= 0)
				return mySide;
			//时间已到
			else if (remainTime <= 0)
				return TankSprite.SIDE_COMP;
			return TankSprite.SIDE_NULL;
		}
		
		private function getEvaluation():int
		{
			var elapseTime:int = battleConfig.battleTime - this.remainTime;
			var evaluation:int = 0;
			while (evaluation < battleConfig.standardTime.length && elapseTime > battleConfig.standardTime[evaluation])
				evaluation++;
			return Math.min(evaluation, battleConfig.standardTime.length - 1);
		}
		
		private function onTick(timer:FlxTimer):void
		{
			if (!inFightFlag)
				return;
			var fightScene:FightScene = SceneManager.getInstance().currentScene as FightScene;
			if (remainTime > 0)
				remainTime--;
			var event:FightEvent = new FightEvent(FightEvent.CLOCK_TICK);
			fightScene.eventDispatcher.dispatchEvent(event);
			var winSide:int = getWinSide();
			var evaluation:int = getEvaluation();
			DebugPane.getInstance().addInfo("winSide: " + winSide + ", enemyExistNum: " + this.enemyExistNum + ", enemyRemainNum: " + this.enemyRemainNum);
			//结束
			if (winSide != TankSprite.SIDE_NULL)
			{
				var campConfig:CampConfig = Config.campConfigs[fightScene.campIndex];
				fightScene.showEndPane(fightScene.campIndex, fightScene.battleOrder, winSide, evaluation);
				//停止心跳
				inFightFlag = false;
				timer.stop();
			}
			//出生敌军坦克			
			if (GuideScene.getInstance().step == 6 || GuideScene.getInstance().step == 7 ||
				GuideScene.getInstance().step == 8)
				return;
			appearEnemies();
		}
		
		private function appearEnemies():void
		{
			var enemyExistMax:int = isHeroMode ? battleConfig.enemyExistMax + 1 : battleConfig.enemyExistMax;
			if (enemyExistNum < enemyExistMax && enemyAppears.length > 0)
			{
				var gameMode:int = FightScene.getInstance().gameMode;
				if (gameMode == FightScene.MODE_FRIEND)
				{
					var friend:PlayerInfo = PlayerInfoManager.getInstance().players[FightScene.getInstance().friendId];
					var tankId:int = enemyAppears[0];
					var tankInfo:TankInfo = PlayerInfoManager.getInstance().tanks[tankId];
					var direction:int = Math.random() * 4;
					var randPos:Point = getRandEmptyPos(); 
					var posX:int = randPos.x;
					var posY:int = randPos.y;
					var enemyBossLevel:int = tankId == friend.campTankId ? 3 : -1; 
					var healthPoint:int = tankId == friend.campTankId ? 3 * tankInfo.healthPoint : tankInfo.healthPoint;
					createTank(tankInfo.id, tankInfo.index, friend.nickname, TankSprite.SIDE_FRIEND, direction, OFFSET_X + TILE_WIDTH * posX, OFFSET_Y + TILE_WIDTH * posY, 
						healthPoint, tankInfo.energyPoint, tankInfo.attackPoint, tankInfo.criticalAttackRatio, tankInfo.armPoint, 
						tankInfo.moveVelocity, tankInfo.fireCooldown + 1000, -1, tankInfo.fightPoint, enemyBossLevel);
					enemyAppears.shift();
				}
				else
				{
					var enemyAppear:EnemyAppearConfig = enemyAppears[0];
					var enemyConfig:EnemyConfig = Config.enemyConfigs[enemyAppear.enemyIndex];
					if (enemyAppear.num > 0)
					{
						tankId = -int.MAX_VALUE * Math.random();
						direction = enemyAppear.direction;
						if (direction < 0)
							direction = Math.random() * 4;
						posX = enemyAppear.posX;
						posY = enemyAppear.posY;
						if (posX < 0 || posY < 0)
						{
							randPos = getRandEmptyPos(); 
							posX = randPos.x;
							posY = randPos.y;
						}
						var campIndex:int = FightScene.getInstance().campIndex;
						var fortIndex:int = Config.campFortLink[campIndex];
						var fortConfig:FortressConfig = Config.fortressConfigs[fortIndex];
						var enemyLevel:int = isHeroMode ? enemyAppear.level + fortConfig.heroMode.enemyLevelIncrease : enemyAppear.level;
						enemyBossLevel = (isHeroMode && enemyAppear.bossLevel > 0) ? enemyAppear.bossLevel + fortConfig.heroMode.enemyBossLevelIncrease : enemyAppear.bossLevel;
						createTank(tankId, enemyConfig.tankIndex, enemyConfig.name, TankSprite.SIDE_COMP, direction, OFFSET_X + TILE_WIDTH * posX, OFFSET_Y + TILE_WIDTH * posY, 
							enemyConfig.healthPoint * enemyLevel + enemyConfig.healthPoint * enemyLevel * enemyBossLevel * 3, 
							enemyConfig.energyPoint * enemyLevel, enemyConfig.attackPoint * enemyLevel, 
							enemyConfig.criticalAttackRatio * enemyLevel, enemyConfig.armPoint * enemyLevel, enemyConfig.moveVelocity, 
							enemyConfig.fireCooldown, enemyConfig.index, enemyLevel, enemyBossLevel);
						enemyAppear.num--;
						if (enemyAppear.num <= 0)
							enemyAppears.shift();
					}
				}
			}
		}
		
		//附加状态奖励
		public function addedStatusAward():void
		{
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			if (me.status != null)
			{
				var award:Object = FightScene.getInstance().awardList[me.campTankId];
				for (var s:String in award)
				{
					var added:int = me.status.getTotalAddedRange(parseInt(s));
					award[s] += award[s] * added / 1000;
				}
			}
		}
		
		public override function destroy():void
		{
			super.destroy();
			enemyAppears = null;
			tileMap = null;
			battleConfig = null;
			tanks = null;
			bullets = null;
			dropItems = null;
			collideBulletGroup.destroy();
			collideBulletGroup = null;
			bulletGroup.destroy();
			bulletGroup = null;
			tankGroup.destroy();
			tankGroup = null;
			dropItemGroup.destroy();
			dropItemGroup = null;
			//TO DO: 
			FightScene.getInstance().effectTopLayer.removeChild(topTileSprite);
		}
	}
}
